import React, { useState, useEffect, useCallback, useRef } from 'react';
import {
  StyleSheet,
  View,
  Text,
  TouchableOpacity,
  Image,
  Alert,
  AppState,
  Platform,
  Dimensions,
} from 'react-native';
import { useRoute, useNavigation, RouteProp } from '@react-navigation/native';
import { RootStackParamList } from '../types';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { Ionicons } from '@expo/vector-icons';
import { useTheme } from '../contexts/ThemeContext';
import * as Notifications from 'expo-notifications';
import { registerBackgroundTask, startTimerService, stopTimerService } from '../utils/backgroundService';

type TimerScreenRouteProp = RouteProp<RootStackParamList, 'Timer'>;

Notifications.setNotificationHandler({
  handleNotification: async () => ({
    shouldShowAlert: true,
    shouldPlaySound: true,
    shouldSetBadge: false,
  }),
});

const TimerScreen: React.FC = () => {
  const route = useRoute<TimerScreenRouteProp>();
  const navigation = useNavigation();
  const { colors } = useTheme();
  const { taskId, taskTitle, coverImage, isPomodoroMode: initialPomodoroMode } = route.params;

  const [isRunning, setIsRunning] = useState(false);
  const [timeLeft, setTimeLeft] = useState(0);
  const [isPomodoroMode, setIsPomodoroMode] = useState(initialPomodoroMode);
  const [isBreak, setIsBreak] = useState(false);
  const [pomodoroCount, setPomodoroCount] = useState(0);
  const [settings, setSettings] = useState({
    workDuration: 25,
    breakDuration: 5,
    longBreakDuration: 15,
    longBreakInterval: 4,
  });

  const lastTimeRef = useRef<number | null>(null);
  const backgroundTimeRef = useRef<number | null>(null);
  const accumulatedTimeRef = useRef<number>(0);

  const windowHeight = Dimensions.get('window').height;
  const windowWidth = Dimensions.get('window').width;

  useEffect(() => {
    const initializeTimer = async () => {
      await loadSettings();
      if (!isPomodoroMode) {
        await loadProgress();
      }
    };
    initializeTimer();
  }, []);

  useEffect(() => {
    if (isPomodoroMode) {
      setTimeLeft(settings.workDuration * 60);
      setIsBreak(false);
      setPomodoroCount(0);
    } else {
      loadProgress();
    }
  }, [isPomodoroMode]);

  useEffect(() => {
    loadSettings();
    registerForPushNotificationsAsync();
    const subscription = AppState.addEventListener('change', handleAppStateChange);

    // 加载上次保存的进度
    loadProgress();

    // 每天凌晨重置计时
    const now = new Date();
    const tomorrow = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1);
    const timeToMidnight = tomorrow.getTime() - now.getTime();
    const resetTimer = setTimeout(() => {
      resetDailyProgress();
    }, timeToMidnight);

    // 组件卸载时清理
    return () => {
      subscription.remove();
      clearTimeout(resetTimer);
      if (isRunning) {
        saveProgress();
        saveTimeRecord();
      }
    };
  }, []);

  useEffect(() => {
    registerBackgroundTask();
  }, []);

  const loadSettings = async () => {
    try {
      const savedSettings = await AsyncStorage.getItem('userSettings');
      if (savedSettings) {
        const { defaultPomodoroSettings } = JSON.parse(savedSettings);
        setSettings(defaultPomodoroSettings);
        if (isPomodoroMode) {
          setTimeLeft(defaultPomodoroSettings.workDuration * 60);
        }
      }
    } catch (error) {
      console.error('加载设置失败:', error);
      if (isPomodoroMode) {
        setTimeLeft(settings.workDuration * 60);
      }
    }
  };

  const loadProgress = async () => {
    try {
      // 检查是否是新的一天
      const lastActiveDate = await AsyncStorage.getItem(`last_active_date_${taskId}`);
      const today = new Date().toDateString();
      if (lastActiveDate && lastActiveDate !== today) {
        await resetDailyProgress();
        await AsyncStorage.setItem(`last_active_date_${taskId}`, today);
        return;
      }

      // 加载今日记录
      const savedRecordsStr = await AsyncStorage.getItem('timeRecords');
      if (savedRecordsStr) {
        const records = JSON.parse(savedRecordsStr);
        const today = new Date().toISOString().split('T')[0];
        const todayRecord = records.find(
          (r: any) => r.taskId === taskId && r.date === today
        );
        
        if (todayRecord) {
          // 从今日记录的时间开始计时（转换为秒）
          setTimeLeft(todayRecord.minutes * 60);
        } else {
          setTimeLeft(0);
        }
      } else {
        setTimeLeft(0);
      }

      // 记录今天的日期
      await AsyncStorage.setItem(`last_active_date_${taskId}`, today);
    } catch (error) {
      console.error('加载进度失败:', error);
    }
  };

  const saveProgress = async () => {
    try {
      const progress = {
        isRunning,
        isPomodoroMode,
        isBreak,
        pomodoroCount,
        timeLeft,
        lastActiveTime: Date.now(),
        accumulatedTime: accumulatedTimeRef.current,
      };
      await AsyncStorage.setItem(`timer_progress_${taskId}`, JSON.stringify(progress));
    } catch (error) {
      console.error('保存进度失败:', error);
    }
  };

  const handleAppStateChange = async (nextAppState: string) => {
    if (nextAppState === 'active') {
      // 从后台恢复时
      if (isRunning && backgroundTimeRef.current !== null) {
        const now = Date.now();
        const timePassed = Math.floor((now - backgroundTimeRef.current) / 1000);
        
        if (isPomodoroMode) {
          // 番茄钟模式：减少时间
          setTimeLeft(prev => {
            const newTime = Math.max(0, prev - timePassed);
            if (newTime === 0) {
              handleTimerComplete();
            }
            return newTime;
          });
        } else {
          // 普通计时模式：增加时间
          setTimeLeft(prev => prev + timePassed);
        }
        
        lastTimeRef.current = now;
        backgroundTimeRef.current = null;
      }
    } else if (nextAppState === 'background' || nextAppState === 'inactive') {
      // 进入后台时记录时间戳
      if (isRunning) {
        backgroundTimeRef.current = Date.now();
        await saveProgress();
      }
    }
  };

  const saveTimeRecord = async () => {
    if (!isRunning) return;

    try {
      const now = new Date();
      const today = now.toISOString().split('T')[0];
      
      // 计算本次计时的时间（转换为分钟，小于1分钟的舍去）
      const minutes = Math.floor(timeLeft / 60);
      if (minutes < 1) return; // 小于1分钟不记录
      
      // 读取现有记录
      const savedRecordsStr = await AsyncStorage.getItem('timeRecords');
      let records: TimeRecord[] = savedRecordsStr ? JSON.parse(savedRecordsStr) : [];
      
      // 查找今天该任务的记录
      const existingRecord = records.find(
        (r) => r.taskId === taskId && r.date === today
      );
      
      const newRecord: TimeRecord = {
        id: existingRecord?.id || now.getTime().toString(),
        taskId,
        date: today,
        minutes: existingRecord ? existingRecord.minutes + minutes : minutes, // 累加时间
        timestamp: now.toISOString(),
        isPomodoroMode,
        pomodoroCount: isPomodoroMode ? pomodoroCount : undefined,
      };

      if (existingRecord) {
        // 更新现有记录
        records = records.map((r) =>
          r.taskId === taskId && r.date === today ? newRecord : r
        );
      } else {
        // 创建新记录
        records.push(newRecord);
      }
      
      // 保存记录
      await AsyncStorage.setItem('timeRecords', JSON.stringify(records));
      
      // 更新任务的今日总时间
      const savedTasksStr = await AsyncStorage.getItem('tasks');
      if (savedTasksStr) {
        const tasks = JSON.parse(savedTasksStr);
        const updatedTasks = tasks.map((task: any) => {
          if (task.id === taskId) {
            return {
              ...task,
              totalTimeToday: formatTimeForDisplay(newRecord.minutes),
            };
          }
          return task;
        });
        await AsyncStorage.setItem('tasks', JSON.stringify(updatedTasks));
      }
    } catch (error) {
      console.error('保存时间记录失败:', error);
    }
  };

  const formatTimeForDisplay = (minutes: number) => {
    if (typeof minutes !== 'number' || isNaN(minutes) || minutes < 1) {
      return '0分钟';
    }

    const hours = Math.floor(minutes / 60);
    const mins = minutes % 60;
    
    const parts = [];
    if (hours > 0) parts.push(`${hours}小时`);
    if (mins > 0 || parts.length === 0) parts.push(`${mins}分钟`);
    
    return parts.join('');
  };

  const toggleTimer = () => {
    if (!isRunning) {
      startTimer();
    } else {
      pauseTimer();
    }
  };

  const startTimer = async () => {
    if (!isRunning) {
      setIsRunning(true);
      // 如果是继续计时，使用当前的 timeLeft
      // 如果是新开始，则使用 0 或番茄钟的初始时间
      lastTimeRef.current = Date.now();
      backgroundTimeRef.current = null;
      await startTimerService(taskTitle);
    }
  };

  const pauseTimer = async () => {
    if (!isRunning) return;
    
    setIsRunning(false);
    await saveTimeRecord();
    lastTimeRef.current = null;
    backgroundTimeRef.current = null;
    await stopTimerService();
  };

  const resetTimer = async () => {
    if (isRunning) {
      await saveTimeRecord();
    }
    setIsRunning(false);
    lastTimeRef.current = null;
    backgroundTimeRef.current = null;
    accumulatedTimeRef.current = 0;
    
    if (isPomodoroMode) {
      setTimeLeft(settings.workDuration * 60);
      setIsBreak(false);
      setPomodoroCount(0);
    } else {
      setTimeLeft(0);
    }
    
    await AsyncStorage.removeItem(`timer_progress_${taskId}`);
    await stopTimerService();
  };

  const formatTime = (seconds: number) => {
    if (typeof seconds !== 'number' || isNaN(seconds)) {
      return '00:00:00';
    }

    const hours = Math.floor(seconds / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    const remainingSeconds = seconds % 60;
    
    return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
  };

  const handleTimerComplete = async () => {
    if (!isBreak) {
      await saveTimeRecord();
    }
    setIsRunning(false);
    lastTimeRef.current = null;
    
    if (!isBreak) {
      // 工作时段结束
      const newCount = pomodoroCount + 1;
      setPomodoroCount(newCount);
      setIsBreak(true);
      
      // 设置休息时间
      const isLongBreak = newCount % settings.longBreakInterval === 0;
      setTimeLeft(isLongBreak ? settings.longBreakDuration * 60 : settings.breakDuration * 60);
      
      // 发送通知
      await schedulePushNotification('工作完成！', '是时候休息一下了。');
    } else {
      // 休息时段结束
      setIsBreak(false);
      setTimeLeft(settings.workDuration * 60);
      await schedulePushNotification('休息结束！', '让我们开始新的工作吧。');
    }
  };

  useEffect(() => {
    let timer: NodeJS.Timeout;
    if (isRunning) {
      timer = setInterval(() => {
        const now = Date.now();
        if (lastTimeRef.current) {
          const delta = Math.floor((now - lastTimeRef.current) / 1000);
          lastTimeRef.current = now;

          if (isPomodoroMode) {
            // 番茄钟模式：倒计时
            setTimeLeft(prev => {
              const newTime = prev - delta;
              if (newTime <= 0) {
                clearInterval(timer);
                handleTimerComplete();
                return 0;
              }
              return newTime;
            });
          } else {
            // 普通计时模式：正计时
            setTimeLeft(prev => prev + delta);
          }
        }
      }, 1000);
    }
    return () => {
      if (timer) {
        clearInterval(timer);
      }
    };
  }, [isRunning, isPomodoroMode]);

  const resetDailyProgress = async () => {
    try {
      // 清除进度
      await AsyncStorage.removeItem(`timer_progress_${taskId}`);
      // 重置今日时间
      const savedTasksStr = await AsyncStorage.getItem('tasks');
      if (savedTasksStr) {
        const tasks = JSON.parse(savedTasksStr);
        const updatedTasks = tasks.map((task: any) => {
          if (task.id === taskId) {
            return {
              ...task,
              totalTimeToday: '0分钟',  // 使用字符串格式
            };
          }
          return task;
        });
        await AsyncStorage.setItem('tasks', JSON.stringify(updatedTasks));
      }
      // 重置计时器状态
      setTimeLeft(0);
      accumulatedTimeRef.current = 0;
    } catch (error) {
      console.error('重置每日进度失败:', error);
    }
  };

  return (
    <View style={[styles.container, { backgroundColor: colors.background }]}>
      <Image 
        source={{ uri: coverImage }} 
        style={[styles.coverImage, { height: windowHeight * 0.25 }]} 
      />
      
      <View style={styles.content}>
        <Text style={[styles.taskTitle, { 
          color: colors.text,
          fontSize: Math.min(windowWidth * 0.06, 24)
        }]}>{taskTitle}</Text>
        
        <View style={[styles.modeIndicator, { marginVertical: windowHeight * 0.02 }]}>
          <Text style={[styles.modeText, { 
            color: colors.textSecondary,
            fontSize: Math.min(windowWidth * 0.04, 16)
          }]}>
            {isPomodoroMode ? '番茄钟模式' : '普通计时模式'}
          </Text>
        </View>

        {isPomodoroMode ? (
          <View style={[styles.pomodoroInfo, { marginBottom: windowHeight * 0.02 }]}>
            <Text style={[styles.pomodoroText, { 
              color: colors.textSecondary,
              fontSize: Math.min(windowWidth * 0.04, 16)
            }]}>
              {isBreak ? '休息时间' : '工作时间'} ({pomodoroCount} 个番茄钟)
            </Text>
          </View>
        ) : (
          <View style={[styles.timerInfo, { marginBottom: windowHeight * 0.02 }]}>
            <Text style={[styles.timerInfoText, { 
              color: colors.textSecondary,
              fontSize: Math.min(windowWidth * 0.04, 16)
            }]}>
              计时中...
            </Text>
          </View>
        )}

        <Text style={[styles.timer, { 
          color: colors.text,
          fontSize: Math.min(windowWidth * 0.18, 72),
          marginBottom: windowHeight * 0.04
        }]}>{formatTime(timeLeft)}</Text>

        <View style={styles.controls}>
          <TouchableOpacity
            style={[styles.controlButton, { 
              backgroundColor: colors.primary,
              width: Math.min(windowWidth * 0.15, 60),
              height: Math.min(windowWidth * 0.15, 60),
              borderRadius: Math.min(windowWidth * 0.075, 30),
            }]}
            onPress={toggleTimer}
          >
            <Ionicons
              name={isRunning ? 'pause' : 'play'}
              size={Math.min(windowWidth * 0.06, 24)}
              color="white"
            />
          </TouchableOpacity>
          
          <TouchableOpacity
            style={[styles.controlButton, { 
              backgroundColor: colors.error,
              width: Math.min(windowWidth * 0.15, 60),
              height: Math.min(windowWidth * 0.15, 60),
              borderRadius: Math.min(windowWidth * 0.075, 30),
            }]}
            onPress={resetTimer}
          >
            <Ionicons 
              name="refresh" 
              size={Math.min(windowWidth * 0.06, 24)} 
              color="white" 
            />
          </TouchableOpacity>
        </View>
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  coverImage: {
    width: '100%',
    resizeMode: 'cover',
  },
  content: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    paddingHorizontal: 20,
  },
  taskTitle: {
    fontWeight: 'bold',
    textAlign: 'center',
  },
  modeIndicator: {
    paddingHorizontal: 16,
    paddingVertical: 8,
    borderRadius: 20,
    backgroundColor: 'rgba(0, 0, 0, 0.1)',
  },
  modeText: {
    fontWeight: '500',
  },
  pomodoroInfo: {
    alignItems: 'center',
  },
  pomodoroText: {
    textAlign: 'center',
  },
  timerInfo: {
    alignItems: 'center',
  },
  timerInfoText: {
    textAlign: 'center',
  },
  timer: {
    fontWeight: 'bold',
    textAlign: 'center',
  },
  controls: {
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    gap: 20,
  },
  controlButton: {
    justifyContent: 'center',
    alignItems: 'center',
  },
});

async function schedulePushNotification(title: string, body: string) {
  await Notifications.scheduleNotificationAsync({
    content: {
      title,
      body,
      sound: true,
    },
    trigger: null,
  });
}

async function registerForPushNotificationsAsync() {
  if (Platform.OS === 'android') {
    await Notifications.setNotificationChannelAsync('default', {
      name: 'default',
      importance: Notifications.AndroidImportance.MAX,
      vibrationPattern: [0, 250, 250, 250],
      lightColor: '#FF231F7C',
    });
  }

  const { status: existingStatus } = await Notifications.getPermissionsAsync();
  let finalStatus = existingStatus;
  if (existingStatus !== 'granted') {
    const { status } = await Notifications.requestPermissionsAsync();
    finalStatus = status;
  }
  if (finalStatus !== 'granted') {
    Alert.alert('提示', '需要通知权限来提醒你休息和工作时间。');
    return;
  }
}

export default TimerScreen; 